// NewTrainingFramework.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "ResourceManager.h"
#include "../Utilities/utilities.h" // if you use STL, please include this line AFTER all other include
#include "Renderer.h"
#include "StateWelcome.h"
#include "HudMaterial.h"
#include "StateStack.h"
#include <conio.h>
#include "Globals.h"
#include "define.h"

int Init ( ESContext *esContext )
{
	ResourceManager::CreateInstance();
	GetResourceManager()->Init("Resource.txt");

	HudMaterial::CreateInstance();
	GetHudMaterial()->Init();

	StateStack::CreateInstance();
	StateWelcome* stateWelcome = new StateWelcome();
	GetStateStack()->SetState(stateWelcome);

	Renderer::CreateInstance();
	GetRenderer()->Init();
	
	return 0;
}

void Draw ( ESContext *esContext )
{
	// Limit FPS
	#if defined WIN32
	DWORD start, end;
	start = GetTickCount();
	#endif

	glClear(GL_COLOR_BUFFER_BIT);
	GetStateStack()->GetCurrentState()->Render();
	eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );

	#if defined WIN32
	// Limit FPS
	end = GetTickCount();
	DWORD deltaTime = end - start;

	if (deltaTime < 1000 / FPS)
	{
	Sleep(1000 / FPS - deltaTime);
	}
	#endif
}

void Update ( ESContext *esContext, float deltaTime )
{
	GetStateStack()->GetCurrentState()->Update(deltaTime/2.0f);
}

void Key ( ESContext *esContext, unsigned char key, bool bIsPressed)
{
	StateBase* state = GetStateStack()->GetCurrentState();
	if (bIsPressed)
	{
		state->OnKeyDown(key);
	}
	else
	{
		state->OnKeyUp(key);
	}
}

void Mouse ( ESContext *esContext, bool bIsClicked, float xPos, float yPos)
{
	StateBase* state = GetStateStack()->GetCurrentState();
	if (bIsClicked)
	{
		state->OnTouchDown(xPos, yPos);
	}
	else
	{
		state->OnTouchUp(xPos, yPos);
	}
}

void CleanUp()
{
	ResourceManager::DestroyInstance();
	Renderer::DestroyInstance();
	StateStack::DestroyInstance();
	HudMaterial::DestroyInstance();
}

int _tmain(int argc, _TCHAR* argv[])
{
	ESContext esContext;

    esInitContext ( &esContext );

	esCreateWindow ( &esContext, "Hello Triangle", Globals::screenWidth, Globals::screenHeight, ES_WINDOW_RGB | ES_WINDOW_DEPTH);

	if ( Init ( &esContext ) != 0 )
		return 0;

	esRegisterDrawFunc ( &esContext, Draw );
	esRegisterUpdateFunc ( &esContext, Update );
	esRegisterKeyFunc ( &esContext, Key );
	esRegisterMouseFunc ( &esContext, Mouse );

	esMainLoop ( &esContext );

	//releasing OpenGL resources
	CleanUp();

	//identifying memory leaks
	MemoryDump();
	printf("Press any key...\n");
	_getch();

	return 0;
}

